<template>
  <div style="height: 100%;display: flex;flex-direction: column;">
    <a-form ref="formRef" :model="formState" name="select" autocomplete="off" layout="inline"
      style=" padding: 5px; display: flex; justify-content: space-between; align-items: center;background-color:white; height: auto;">
      <div style="width: 100%; display: flex; justify-content: space-between;">
        <div style="display: flex;  flex-wrap: wrap; width: 85%;">
          <a-form-item label="姓名/学号" name="StudentName" style="padding:5px ">
            <a-input v-model:value="formState.StudentName" placeholder="输入学生姓名或学号" />
          </a-form-item>

          <a-form-item label="专业" name="StudentMajor" style="padding:5px">
            <a-input v-model:value="formState.StudentMajor" placeholder="输入学生专业" />
          </a-form-item>
        </div>
        <div style="display: flex; width: auto;">
          <a-button style="margin-right: 10px; margin-top: 5px;" type="primary" :icon="h(SearchOutlined)"
            @click="onSubmit" :loading="loading">查询</a-button>
          <a-button style="margin-right: 5px; margin-top: 5px; ;" :icon="h(RedoOutlined)"
            @click="resetForm" :loading="loading">重置</a-button>
        </div>
      </div>
    </a-form>
    <a-table :columns="columns" :data-source="data" row-key="userId" :scroll="{ y: '49vh' }" 
      :pagination="{ 
        current: currentPage, 
        pageSize: pageSize, 
        total: total, 
        showSizeChanger: true, 
        showTotal: (total) => `共 ${total} 条记录`, 
        position: ['bottomCenter'] 
      }" 
      :row-selection="rowSelection"
      :expanded-row-keys="expandedRowKeys" 
      @expand="onExpand" 
      @change="handleTableChange"
      :loading="loading"
      :bordered="true">
      <template #expandedRowRender="{ record }">
        <span style="font-weight: bold; margin-right: 2%;">相关任务成绩</span>
        <a @click="visible1 = true" style="margin-right: 2% " v-for="taskGrade in record.taskGrades" :key="taskGrade.taskId">
          {{ taskGrade.taskName }}: {{ taskGrade.finalScore }}
        </a>
      </template>
      <template #expandColumnTitle>
        <a-switch v-model:checked="alltoExpand" size="small" @click="allExpand" />
      </template>
    </a-table>
  </div>
  <StudentTaskDetail :values="task" :modelVisible="visible1" @update:modelVisible="(val) => { visible1 = val }" />
</template>
<script lang="ts" setup>
import { computed, ref, unref, onMounted, watch } from 'vue';
import { h, reactive } from 'vue';
import { SearchOutlined, RedoOutlined } from '@ant-design/icons-vue';
import type { FormInstance } from 'ant-design-vue';
import StudentTaskDetail from './StudentTaskDetail.vue';
import dayjs from 'dayjs';
import CourseDao from '@/daos/course_dao';
import { message } from 'ant-design-vue';

// 表单对应数据接口
interface FormState {
  StudentName: string | number;
  StudentMajor: string;
}

//表格对应的数据接口
interface FormStateTable {
  userId: number;
  name: string;
  className: string;
  teamName: string;
  totalScore: number;
  taskGrades?: any[]
}

// 表单对应数据
const formState = reactive<FormState>({
  StudentName: '',
  StudentMajor: '',
});

// 接收的属性
const props = defineProps({
  teamId: {
    type: Number,
    default: 0
  },
  courseId: {
    type: Number,
    required: true
  },
  classId: {
    type: Number,
    default: null
  }
});

// 课程DAO
const courseDao = new CourseDao();
// 加载状态
const loading = ref(false);
// 当前页码
const currentPage = ref(1);
// 每页条数
const pageSize = ref(10);
// 总记录数
const total = ref(0);

// 任务详情数据
const task = ref({
  taskName: "学生表设计",
  projectName: "项目式教学",
  moduleName: "数据库设计-1",
  taskStatus: "进行中",
  taskDescription: "根据需求分析完成学生表设计",
  createTime: dayjs(),
  endTime: dayjs(),
  startTime: dayjs(),
  finishTime: dayjs(),
  achievement: [{
    achievementId: 1,
    achievementName: "学生表",
    deliverableName: "交付物1",
  }, {
    achievementId: 2,
    achievementName: "教师表",
    deliverableName: "交付物2",
  }],
  teacherScore: 100,
  managerScore: null,
});

// 任务弹窗
const visible1 = ref(false);
// 表单Ref
const formRef = ref<FormInstance>();

// 表格默认列对象
const columns = ref([
  {
    title: '学号',
    dataIndex: 'userId',
    align: 'center' as 'center',
    width: '20%',
  },
  {
    title: '姓名',
    dataIndex: 'name',
    align: 'center' as 'center',
    width: '20%',
  },
  {
    title: '所属项目班',
    dataIndex: 'className',
    align: 'center' as 'center',
    width: '20%',
  },
  {
    title: '所属小组',
    dataIndex: 'teamName',
    align: 'center' as 'center',
    width: '20%',
  },
  {
    title: '总分',
    dataIndex: 'totalScore',
    align: 'center' as 'center',
    width: '20%',
  }
]);

// 表格数据源存储对象
const data = ref<FormStateTable[]>([]);

// 表格多选内容
const selectedRowKeys = ref<FormStateTable['userId'][]>([]);
const selectedall = ref(true);
const rowSelection = computed(() => {
  return {
    selectedRowKeys: unref(selectedRowKeys),
    onSelect: (record: FormStateTable, selected: boolean) => {
      if (selected)
        selectedRowKeys.value.push(record.userId);
      else {
        const index = selectedRowKeys.value.indexOf(record.userId);
        selectedRowKeys.value.splice(index, 1);
      }
    },
    onSelectAll: () => {
      if (selectedall.value) {
        const allRowKeys = data.value.map(item => item.userId);
        selectedRowKeys.value = allRowKeys;
        selectedall.value = !selectedall.value;
      }
      else {
        selectedRowKeys.value = [];
        selectedall.value = !selectedall.value;
      }
    },
    hideDefaultSelections: true,
  };
});

// 扩展行内容key数组
const expandedRowKeys = ref([]);

// 单独展开收缩列
const onExpand = (expanded: boolean, record: any) => {
  if (expanded == true)
    expandedRowKeys.value.push(record.userId);
  else {
    const index = expandedRowKeys.value.indexOf(record.userId);
    expandedRowKeys.value.splice(index, 1);
  }
};

// 一件展开收缩全部扩展列
const alltoExpand = ref(true);
const allExpand = () => {
  if (alltoExpand.value) {
    const allRowKeys = data.value.map(item => item.userId);
    expandedRowKeys.value = allRowKeys;
  }
  else {
    expandedRowKeys.value = [];
  }
};

// 获取学生成绩数据
const fetchStudentGrades = async () => {
  loading.value = true;
  try {
    const params = {
      courseId: props.courseId,
      classId: props.classId,
      teamId: props.teamId !== 0 ? props.teamId : null,
      studentName: formState.StudentName,
      studentMajor: formState.StudentMajor,
      currentPage: currentPage.value - 1, // 后端从0开始计数
      pageSize: pageSize.value
    };
    
    console.log('获取学生成绩数据，参数:', params);
    const result = await courseDao.getCourseGrades(params);
    console.log('获取学生成绩数据结果:', result.data);

    if (result.data.code === 200 && result.data.data) {
      data.value = result.data.data.rows || [];
      total.value = result.data.data.totalCount || 0;
      
      console.log('学生成绩数据:', data.value);
      console.log('总记录数:', total.value);

      // 如果启用了全部展开，则展开所有行
      if (alltoExpand.value) {
        const allRowKeys = data.value.map(item => item.userId);
        expandedRowKeys.value = allRowKeys;
      }
    } else {
      console.error('获取学生成绩数据失败:', result.data);
      message.error('获取学生成绩数据失败');
    }
  } catch (error) {
    console.error('获取学生成绩数据失败', error);
    message.error('获取学生成绩数据失败');
  } finally {
    loading.value = false;
  }
};

// 提交筛选内容
const onSubmit = () => {
  currentPage.value = 1; // 重置到第一页
  fetchStudentGrades();
};

// 清空筛选框内容
const resetForm = () => {
  formRef.value.resetFields();
  currentPage.value = 1; // 重置到第一页
  fetchStudentGrades();
};

// 分页变化
const handleTableChange = (pagination) => {
  currentPage.value = pagination.current;
  pageSize.value = pagination.pageSize;
  fetchStudentGrades();
};

// 监听属性变化
watch([() => props.courseId, () => props.classId, () => props.teamId], () => {
  currentPage.value = 1; // 重置到第一页
  fetchStudentGrades();
});

// 初始化
onMounted(() => {
  fetchStudentGrades();
});
</script>


<style scoped>
th.column-money,
td.column-money {
  text-align: right !important;
}

a {

  color: #61666d;
}

a:hover {
  color: #00aeec;
}
</style>